package com.feiyue.learning.product_service.zk;

import org.I0Itec.zkclient.ZkClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RegisterService {
    private static Logger LOGGER = LoggerFactory.getLogger(RegisterService.class);
    private static final String ZK_CONNECTION = "127.0.0.1:2181";
    private static final String BASE_SERVICE = "/service";

    /*
     * serviceName: 要注册的服务的名称, 也是 zk 节点的名称
     * host: 要注册的服务的 ip
     * port: 要注册的服务的端口
     * ip + port 作为节点数据
     */
    public static void register(String serviceName, String host, int port) {

        ZkClient zkClient = new ZkClient(ZK_CONNECTION, 5000);

        if (!zkClient.exists(BASE_SERVICE)) {
            zkClient.createPersistent(BASE_SERVICE);
        }

        String value = host + ":" + port;

        // 创建临时有序节点因为随着服务异常对应的节点需要自动删除，其次由于服务可能要做高可用，所以需要是顺序节点
        zkClient.createEphemeralSequential(BASE_SERVICE.concat("/").concat(serviceName), value);
        LOGGER.info("{} 服务注册成功", serviceName);

        // 此处不能关闭 zkClient, 因为这个服务注册(临时节点)上去就一直提供服务

    }
}
